package com.action;
import java.util.Locale;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import com.beans.UserInfo;
import com.dao.UserDao;

@Controller
public class UserAction {
	
	//用于国际化
	@Resource 
	private MessageSource messageSource;
	
	@Resource
	private UserDao userDao;
	
	//注意,这里配置了访问 login.html 在这处理
	@GetMapping(value={"/login"})
	public String gotoLogin() {
		return "login";
	}
	
	@PostMapping(value={"/login"})
	public String login(String userName,String password,ModelMap m, HttpServletRequest request) {
		if("admin".equals(userName) && "123".equals(password)) {
			UserInfo user=new UserInfo();
			user.setUserName("admin");
			user.setPassword("123");
			
			request.getSession().setAttribute("session_user", user);
			return "main"; 
		}
		else {
			Locale locale = LocaleContextHolder.getLocale();
			String msg=messageSource.getMessage("loginerror",null, locale); 
			m.put("msg", msg);
			return "login";
		}	 
	}

	//查询所有用户列表
	@GetMapping("/users")
	public String findAll(ModelMap map) {
		
		map.put("usersList", userDao.getUserList());
		return "user-pages/user-manager";
	}
	
	//转到用户添加界面
	@GetMapping("/user")
    public String toAddPage(){
        return "user-pages/user-add";
    }
	
	//真正的进行用户添加,实际上用户修改走的也是这个方法,内部会根据有没有id进行区分
	@PostMapping("/user")
    public String addUser(UserInfo user){
		userDao.save(user);
        return "redirect:/users";
    }
	
	//来到修改页面，查出当前用户，在页面回显
    @GetMapping("/user/{id}")
    public String toEditPage(@PathVariable("id") Integer id, Model model){
        UserInfo user = userDao.getUserById(id);
        model.addAttribute("user", user);
        //回到修改页面(user-add是一个修改添加二合一的页面);
        return "user-pages/user-add";
    }
    
    @GetMapping("/delete/{id}")
    public String deleteUser(@PathVariable("id") Integer id){
        userDao.deleteUserById(id);
        return "redirect:/users";
    }
    
    /* 下两面两个方式, 要配置: spring.mvc.hiddenmethod.filter.enabled=true  
    //用户修改；需要提交员工id
    @PutMapping("/user")
    public String updateUser(UserInfo user){
    	userDao.save(user);
        return "redirect:/users";
    }
    
    //用户删除
    @DeleteMapping("/user/{id}")
    public String deleteUser(@PathVariable("id") Integer id){
        userDao.deleteUserById(id);
        return "redirect:/users";
    }
    */
}
